<?php

namespace app\api\model;
use app\api\service\Payment as PaymentService;
use app\api\service\card\PaySuccess;
use app\common\enum\order\PayType as PayTypeEnum;
use app\common\enum\OrderType as OrderTypeEnum;
use app\common\exception\BaseException;
use app\common\model\CardOrder as CardOrderModel;
use app\common\model\store\Shop as ShopModel;
use app\common\service\Order;
class CardOrder extends CardOrderModel
{
    /**
     * 获取预定时间
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function fixedTime(){
        $datearr = [];$timearr=[];
        for ($i=0; $i<=10; $i++){
            $datearr[] = date("Y-m-d",strtotime("{$i} day"));
        }
        $data = ShopModel::order('shop_id', 'desc')->limit(1)->select()->toArray();
        if(!empty($data[0]) && !empty($data[0]['shop_hours'])){
            list($startTime,$endTime) = explode('-',$data[0]['shop_hours']);
            if((int)$endTime<(int)$startTime){//就是隔一天
                $enddate = strtotime(date("Y-m-d {$endTime}:00",strtotime("1 day")));
                $startdate = strtotime(date("Y-m-d {$startTime}:00",time()));
                $hours =floor(($enddate-$startdate)/3600);
                for($j=0; $j<=$hours; $j++){
                    $second = $j*3600;
                    $time = (int)date('H:00',strtotime(date("Y-m-d {$startTime}:00",time()))+$second);
                    if(strlen($time)>1){
                        $arr['time'] = "今日 ".date('H:00',strtotime(date("Y-m-d {$startTime}:00",time()))+$second);
                        $arr['sign']=1;
                    }else{
                        $arr['time'] = "次日 ".date('H:00',strtotime(date("Y-m-d {$startTime}:00",time()))+$second);
                        $arr['sign']=2;
                    }

                    $arr['hour'] = date('H:00',strtotime(date("Y-m-d {$startTime}:00",time()))+$second);
                    $timearr[] = $arr;
                }
            }elseif ((int)$endTime>(int)$startTime){
                $startdate = strtotime(date("Y-m-d {$startTime}:00",time()));
                $enddate = strtotime(date("Y-m-d {$endTime}:00",time()));
                $hours =floor(($enddate-$startdate)/3600);
                for($j=0; $j<=$hours; $j++){
                    $second = $j*3600;
                    $arr['time'] = "今日 ".date('H:00',strtotime(date("Y-m-d {$startTime}:00",time()))+$second);
                    $arr['hour'] = strtotime(date("Y-m-d {$startTime}:00",time()))+$second;
                    $timearr[] = $arr;
                }
            }
        }
        return ['date'=>$datearr,'time'=>$timearr];
    }
    //创建卡座订单
    public static function createOrder($order){
        // 订单模型
        $model = new self;$appointment_time='';
        if(!empty($order['sign']) && $order['sign']==2){
            $timestamp = strtotime($order['date'])+24*3600;
            $appointment_time = date('Y-m-d',$timestamp)." {$order['hour']}";
        }else{
            $appointment_time = $order['date']." {$order['hour']}";
        }
        $data = [
            'order_no'=>Order::createCardOrderNo(),
            'user_id'=>$order['user_id'],
            'shop_id'=>$order['shop_id'],
            'clerk_id'=>$order['clerk_id'],
            'pay_amount'=>$order['pay_amount'],
            //'pay_type' =>$order['pay_type'],
            'subscribe_name'=>$order['subscribe_name'],
            'mobile'=>$order['mobile'],
            'expense'=>$order['expense'],
            'appointment_time'=>$appointment_time,
            'wxapp_id' => $model::$wxapp_id
        ];
        // 保存订单记录
          //$result = $model->insertGetId($data);
          $result = $model->save($data);
          return $model->id;

    }

    /**
     * 获取卡座订单信息
     * @param $clerk_id
     * @return array|bool|\PDOStatement|string|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getDetail($card_id,$user_id){
        $result = self::alias('co')->join('store_shop_clerk ssc ','co.clerk_id=ssc.clerk_id','left')->field('co.*,ssc.real_name as card_name,ssc.mobile as represent')->where([
            'co.id'=>$card_id,
            'co.user_id' => $user_id,
        ])->find();
        return $result;
    }

    /**
     * 获取卡座订单列表信息
     * @param $clerk_id
     * @return array|bool|\PDOStatement|string|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getList($order_status,$user_id){
        $where['co.user_id']=$user_id;
        if(empty($order_status)){
            $where['co.order_status'] = ['<>',0];
        }else{
            $where['co.order_status'] = $order_status;
        }
        $result = self::alias('co')->field('co.*,ssc.real_name as card_name,ssc.mobile as represent')->join('store_shop_clerk ssc','co.clerk_id=ssc.clerk_id','left')->where($where)->select();
        return $result;
    }
    /**
     * 获取卡座订单列表信息
     * @param $clerk_id
     * @return array|bool|\PDOStatement|string|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getWrite($user_id){
        $where['co.user_id']=$user_id;
        $where['co.appointment_time'] = ['like',"%".date('Y-m-d',time())."%"];
        $where['co.order_status'] = self::CARD_ORDER_FINISH;
        $result = self::alias('co')->field('co.*,ssc.real_name as card_name,ssc.mobile as represent')->join('store_shop_clerk ssc','co.clerk_id=ssc.clerk_id','left')->where($where)->select();
        return $result;
    }
    /**
     * 待支付订单详情
     * @param $orderNo
     * @return null|static
     * @throws \think\exception\DbException
     */
    public static function getPayDetail($orderNo)
    {
        return self::get(['order_no' => $orderNo, 'is_pay' => 0]);
    }

    /**
     * 待支付订单详情
     * @param $orderNo
     * @return null|static
     * @throws \think\exception\DbException
     */
    public static function getOrderDetail($orderNo)
    {
        return self::get(['order_no' => $orderNo]);
    }

    /**
     * 获取订单香型
     * @param $card_id
     * @param $user_id
     * @return array|bool|\PDOStatement|string|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getUserOrderDetail($card_id,$user_id){
        $result = self::alias('co')->join('store_shop_clerk ssc ','co.clerk_id=ssc.clerk_id','left')->field('co.*,ssc.real_name as card_name,ssc.mobile as represent')->where([
            'co.id'=>$card_id,
            'co.user_id' => $user_id,
        ])->find();
        return $result;
    }
    /**
     * 订单支付事件
     * @param int $payType
     * @return bool
     * @throws \think\exception\DbException
     */
    public function onPay($payType = PayTypeEnum::WECHAT)
    {
        /*// 判断商品状态、库存
        if (!$this->checkGoodsStatusFromOrder($this['goods'])) {
            return false;
        }*/
        // 余额支付
        if ($payType == PayTypeEnum::BALANCE) {
            return $this->onPaymentByBalance($this['order_no']);
        }
        return true;
    }

    /**
     * 构建支付请求的参数
     * @param $user
     * @param $order
     * @param $payType
     * @return array
     * @throws BaseException
     * @throws \think\exception\DbException
     */
    public function onOrderPayment($user, $order, $payType)
    {
        if ($payType == PayTypeEnum::WECHAT) {
            return $this->onPaymentByWechat($user, $order);
        }
        return [];
    }

    /**
     * 构建微信支付请求
     * @param $user
     * @param $order
     * @return array
     * @throws BaseException
     * @throws \think\exception\DbException
     */
    private function onPaymentByWechat($user, $order)
    {
        return PaymentService::wechat(
            $user,
            $order['id'],
            $order['order_no'],
            $order['pay_amount'],
            OrderTypeEnum::CARD
        );
    }

    /**
     * 余额支付标记订单已支付
     * @param $orderNo
     * @return bool
     * @throws \think\exception\DbException
     */
    public function onPaymentByBalance($orderNo)
    {
        // 获取订单详情
        $PaySuccess = new PaySuccess($orderNo);
        // 发起余额支付
        $status = $PaySuccess->onPaySuccessBalance(PayTypeEnum::BALANCE);
        if (!$status) {
            $this->error = $PaySuccess->getError();
        }
        return $status;
    }
}